<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <h2>个人信息</h2>
          <el-button type="primary" @click="toggleEdit" v-if="!isEditing">
            <el-icon><Edit /></el-icon>
            编辑信息
          </el-button>
          <div v-else>
            <el-button type="success" @click="saveProfile">
              <el-icon><Check /></el-icon>
              保存
            </el-button>
            <el-button @click="cancelEdit">
              <el-icon><Close /></el-icon>
              取消
            </el-button>
          </div>
        </div>
      </template>

      <div class="profile-content">
        <div class="profile-avatar">
          <el-avatar :size="120" class="avatar">
            {{ userInfo?.name?.charAt(0) || 'U' }}
          </el-avatar>
          <div class="avatar-actions" v-if="isEditing">
            <el-button size="small" text>更换头像</el-button>
          </div>
        </div>

        <div class="profile-form">
          <el-form
            ref="profileFormRef"
            :model="profileForm"
            :rules="rules"
            label-width="120px"
            :disabled="!isEditing"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="profileForm.username" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="真实姓名" prop="name">
                  <el-input v-model="profileForm.name" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="profileForm.email" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="profileForm.phone" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="部门">
                  <el-input v-model="profileForm.department" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="职位" prop="position">
                  <el-input v-model="profileForm.position" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="角色">
                  <el-tag type="primary">{{ getRoleName(profileForm.role) }}</el-tag>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="工号" prop="employeeId">
                  <el-input v-model="profileForm.employeeId" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="个人简介" prop="bio">
              <el-input
                v-model="profileForm.bio"
                type="textarea"
                :rows="4"
                placeholder="请输入个人简介"
              />
            </el-form-item>
          </el-form>
        </div>

        <div class="profile-stats">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-card class="stat-card">
                <div class="stat-item">
                  <div class="stat-value">{{ userStats.loginCount }}</div>
                  <div class="stat-label">登录次数</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="stat-card">
                <div class="stat-item">
                  <div class="stat-value">{{ userStats.assessmentCount }}</div>
                  <div class="stat-label">参与测评</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="stat-card">
                <div class="stat-item">
                  <div class="stat-value">{{ formatDate(userInfo?.lastLoginTime) }}</div>
                  <div class="stat-label">最后登录</div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-card>

    <!-- 修改密码弹窗 -->
    <el-dialog v-model="passwordDialogVisible" title="修改密码" width="400px">
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="当前密码" prop="currentPassword">
          <el-input
            v-model="passwordForm.currentPassword"
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updatePassword">确认修改</el-button>
      </template>
    </el-dialog>

    <!-- 快捷操作 -->
    <el-card class="quick-actions-card">
      <template #header>
        <h3>快捷操作</h3>
      </template>
      <div class="quick-actions">
        <el-button @click="passwordDialogVisible = true">
          <el-icon><Lock /></el-icon>
          修改密码
        </el-button>
        <el-button @click="exportProfile">
          <el-icon><Download /></el-icon>
          导出信息
        </el-button>
        <el-button @click="viewActivityLog">
          <el-icon><Document /></el-icon>
          活动日志
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useUserStore } from '../stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Edit,
  Check,
  Close,
  Lock,
  Download,
  Document
} from '@element-plus/icons-vue'

const userStore = useUserStore()
const profileFormRef = ref()
const passwordFormRef = ref()

// 状态管理
const isEditing = ref(false)
const passwordDialogVisible = ref(false)

// 用户信息
const userInfo = computed(() => userStore.user)

// 表单数据
const profileForm = reactive({
  username: '',
  name: '',
  email: '',
  phone: '',
  department: '',
  position: '',
  role: '',
  employeeId: '',
  bio: ''
})

// 密码表单
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 用户统计数据
const userStats = reactive({
  loginCount: 42,
  assessmentCount: 15,
  lastLoginTime: new Date()
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 密码验证规则
const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 初始化表单数据
const initFormData = () => {
  if (userInfo.value) {
    Object.assign(profileForm, {
      username: userInfo.value.username || '',
      name: userInfo.value.name || '',
      email: userInfo.value.email || '',
      phone: userInfo.value.phone || '',
      department: userInfo.value.department || '',
      position: userInfo.value.position || '',
      role: userInfo.value.role || '',
      employeeId: userInfo.value.employeeId || '',
      bio: userInfo.value.bio || ''
    })
  }
}

// 切换编辑模式
const toggleEdit = () => {
  isEditing.value = true
}

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false
  initFormData() // 重置表单数据
}

// 保存个人信息
const saveProfile = async () => {
  try {
    await profileFormRef.value.validate()

    // 调用 store 更新用户信息
    await userStore.updateProfile(profileForm)

    isEditing.value = false
    ElMessage.success('个人信息更新成功')
  } catch (error) {
    ElMessage.error('请检查表单信息')
  }
}

// 修改密码
const updatePassword = async () => {
  try {
    await passwordFormRef.value.validate()

    // 调用 store 修改密码
    const result = await userStore.updatePassword(passwordForm)

    if (result.success) {
      passwordDialogVisible.value = false
      Object.assign(passwordForm, {
        currentPassword: '',
        newPassword: '',
        confirmPassword: ''
      })
      ElMessage.success('密码修改成功')
    } else {
      ElMessage.error(result.message || '密码修改失败')
    }
  } catch (error) {
    ElMessage.error('请检查表单信息')
  }
}

// 获取角色名称
const getRoleName = (role) => {
  const roleMap = {
    admin: '系统管理员',
    manager: '部门经理',
    user: '普通用户'
  }
  return roleMap[role] || '未知角色'
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '--'
  return new Date(date).toLocaleDateString()
}

// 导出个人信息
const exportProfile = () => {
  ElMessage.info('导出权限不够...')
}

// 查看活动日志
const viewActivityLog = () => {
  ElMessage.info('活动日志权限不够...')
}

onMounted(() => {
  initFormData()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.profile-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  color: #303133;
}

.profile-content {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.profile-avatar {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.avatar {
  font-size: 48px;
  font-weight: bold;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.avatar-actions {
  margin-top: 10px;
}

.profile-form {
  flex: 1;
}

.profile-stats {
  margin-top: 20px;
}

.stat-card {
  text-align: center;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.stat-item {
  padding: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.quick-actions-card {
  margin-top: 20px;
}

.quick-actions {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.quick-actions .el-button {
  display: flex;
  align-items: center;
  gap: 5px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-container {
    padding: 10px;
  }

  .card-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }

  .quick-actions {
    justify-content: center;
  }
}
</style>
